package io.github.lee.jel.ui.item.detail

import android.app.Application
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import dagger.hilt.android.lifecycle.HiltViewModel
import io.github.lee.core.vm.BaseViewModel
import io.github.lee.jel.R
import io.github.lee.jel.domain.ItemDetail
import io.github.lee.core.vm.err.DataParseFailedException
import io.github.lee.jel.err.ResponseFailException
import io.github.lee.jel.global.session
import io.github.lee.jel.repository.ItemRepository
import javax.inject.Inject

@HiltViewModel
class ItemDetailVM @Inject constructor(
    application: Application,
    private val repo: ItemRepository
) : BaseViewModel(application) {
    private val _detailLiveData = MutableLiveData<ItemDetail?>()
    val detailLiveData: LiveData<ItemDetail?> = _detailLiveData


    fun itemDetail(itemId: String?) {
        if (null != _detailLiveData.value) {
            _detailLiveData.postValue(_detailLiveData.value)
            return
        }
        if (itemId.isNullOrEmpty()) {
            toast(getString(R.string.error_param_missing))
            return
        }
        val userId = mContext.session?.userId
        launchResult(
            block = { repo.itemDetail(userId, itemId) },
            error = {
                error(it)
            }
        ) {
            if (!it.isSuccess) {
                error(ResponseFailException(it))
                return@launchResult
            }
            val data = it.data
            if (null == data) {
                error(DataParseFailedException(mContext))
                return@launchResult
            }
            _detailLiveData.postValue(data)
        }

    }
}